<template>
  <div class="monthStatementBox">
    <!-- 头部 标题 -->
    <div class="monthStatementTop">
      <div class="title">
        <span>工资报表</span>
      </div>
    </div>

    <div class="monthStatementTable">
      <!-- 导出按钮 -->
      <div class="export">
        <el-button class="exportBtn" type="primary" size="small" @click="exportSalary">导出</el-button>
      </div>

      <!-- 表格 -->
      <el-table :data="stateData" border style="width: 100%" :header-cell-style="tableHeaderStyle">
        <el-table-column label="序号" width="50" type="index" />
        <el-table-column prop="username" label="姓名" width="180" />
        <el-table-column prop="mobile" label="手机号" width="180" />
        <el-table-column prop="workNumber" label="工号" width="180" />
        <el-table-column prop="departmentName" label="部门名称" width="180" />
        <el-table-column prop="inServiceStatus" label="在职状态" width="180" :formatter="inServiceStatus" />
        <el-table-column prop="providentFundIndividual" label="公积金个人" width="180" />
        <el-table-column prop="socialSecurityIndividual" label="社保个人" width="180" />
        <el-table-column prop="socialSecurityEnterprise" label="社保企业" width="180" />
        <el-table-column prop="providentFundEnterprises" label="公积金企业" width="180" />
        <el-table-column prop="socialSecurityProvidentFundEnterprises" label="公积金社保企业" width="180" />
        <el-table-column prop="currentBaseSalary" label="基本工资" width="180" />
        <el-table-column prop="currentBaseSalary" label="岗位工资" width="180" />
        <el-table-column prop="salaryChangeAmount" label="福利津贴" width="180" />
        <el-table-column prop="attendanceDeductionMonthly" label="考勤扣款" width="180" />
        <el-table-column prop="currentSalaryTotalBase" label="税前工资合计" width="180" />
        <el-table-column prop="salaryByTax" label="应纳税工资" width="180" />
        <el-table-column prop="tax" label="应扣税" width="180" />
        <el-table-column prop="payment" label="实发工资" width="180" />
      </el-table>
    </div>

    <!-- 底部三个按钮 -->
    <el-row type="flex" justify="center" align="middle" style="height:60px">
      <el-col :span="6">
        <el-button size="small" type="primary" @click="archivingReportForm">归档{{ yearMonth ? yearMonth.substr(4) : '' }}月报表</el-button>
        <el-button size="small" type="primary" @click="createReportForm">新建报表</el-button>
        <el-button size="small" @click="$router.back()">取消</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// import { getSalarysDetailByYear, newReport, getArchivingArchive } from '@/api/salarys'
import { getSalarysDetailByYear, newReport } from '@/api/salarys'
export default {
  data() {
    return {
      stateData: [],
      yearMonth: this.$route.params.yearMonth
    }
  },
  created() {
    this.getSalarysDetailByYear()
  },
  methods: {
    //   在职状态 数据 格式化
    inServiceStatus(row) {
      return row.inServiceStatus === '1' ? '在职' : '离职'
    },
    // 导出处理函数
    async exportSalary() {
      const { export_json_to_excel } = await import('@/vendor/Export2Excel')
      //   console.log(export_json_to_excel)
      // 设置字典，因为得到的数据属性是英文，而我们需要中文输出，所以要用字典进行转换
      const dict = {
        '姓名': 'username',
        '手机号': 'mobile',
        '工号': 'workNumber',
        '部门名称': 'departmentName',
        '在职状态': 'inServiceStatus',
        '公积金个人': 'providentFundIndividual',
        '社保个人': 'socialSecurityIndividual',
        '社保企业': 'socialSecurityEnterprise',
        '公积金企业': 'providentFundEnterprises',
        '公积金社保企业': 'socialSecurityProvidentFundEnterprises',
        '基本工资': 'currentBaseSalary',
        '岗位工资': 'currentBaseSalary',
        '福利津贴': 'salaryChangeAmount',
        '考勤扣款': 'attendanceDeductionMonthly',
        '税前工资合计': 'currentSalaryTotalBase',
        '应纳税工资': 'salaryByTax',
        '应扣税': 'tax',
        '实发工资': 'payment'
      }

      const userSalary = this.stateData.map(user => {
        return this.Object2Array(user, dict)
      })
      //   console.log(userSalary)
      export_json_to_excel({
        header: Object.keys(dict),
        data: userSalary
      })
    },
    // 把对象转换成数组 处理函数
    Object2Array(user, dict) {
      const newUser = []
      for (const key in dict) {
        const enKey = dict[key]
        const value = user[enKey]
        if (enKey === 'inServiceStatus') {
          newUser.push(value === '1' ? '在职' : '离职')
        } else {
          newUser.push(value)
        }
      }
      return newUser
    },
    // 获取用户薪资详情数据 处理函数
    async getSalarysDetailByYear() {
      this.stateData = await getSalarysDetailByYear({ yearMonth: this.yearMonth, opType: 1 })
      console.log(this.stateData)
    },
    // 归档报表处理函数
    async archivingReportForm() {
      // 询问用户是否真的要归档报表
      await this.$confirm('您确认归档当月报表吗？(报表归档将覆盖上一次归档记录，无法恢复)')
      // 发送请求
      // await getArchivingArchive(this.yearMonth)
      // 提醒用户
      this.$message.success('归档成功')
    },
    // 新建报表处理函数
    async createReportForm() {
      // 获取到下一个月份
      const yearMonth = this.nextMonth(this.yearMonth)
      const year = yearMonth.substring(0, 4)
      const month = yearMonth.substring(4)
      // 询问用户
      await this.$confirm(`您将创建${year}年${month}月的报表`)
      // 发送请求
      await newReport({ yearMonth: this.yearMonth })
      // 提示用户
      this.$message.success('新建成功')
      //   重新加载页面：因为路由携带了参数，而我们需要改变的参数也需要跟着改变，所以需要跳转页面，调用获取到下一个月数的函数
      this.$router.push(
        { name: this.$route.name,
          params: {
            yearMonth: this.nextMonth(this.$route.params.yearMonth)
          }
        }
      )
    },
    // 得到下一个年月的处理函数
    nextMonth(str) {
      // 拿到需要增加的月数，不管怎么样都先增加1，注意点：需要转换成字符串才能使用substring方法
      let nextMonth = (Number(str) + 1).toString()
      let year = str.substring(0, 4)
      let month = str.substring(4)
      if (month >= 12) {
        year++
        month = '01'
        nextMonth = year + month
      }
      return nextMonth
    },
    // 设置表头单元格背景颜色 处理函数
    tableHeaderStyle({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return 'background:#fafafa'
      } else {
        return ''
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "./../../styles/variables.scss";
.monthStatementBox {
  padding: 20px;
  .monthStatementTop {
    position: relative;
    background: #fff;
    padding: 10px 15px 0 15px;
    border-bottom: solid 1px #f4f4f4;
    .title {
      color: $blue;
      line-height: 40px;
      border-bottom: solid 2px $blue;
      font-size: 18px;
      font-weight: bold;
      display: inline-block;
      padding: 0 25px;
      .yearChange {
        position: absolute;
        top: 5px;
        right: 10px;
      }
    }
  }
  .monthStatementTable{
      position: relative;

  .export{
    height: 50px;
      .exportBtn{
          position: absolute;
          right: 10px;
          top: 10px;
      }
  }
  }

}
</style>
